package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {

	private static Connection conn;

	private DBUtil() {
	}

	private static Connection getConnection() throws SQLException {
		String url = "jdbc:mysql://127.0.0.1/gradapp";
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		conn = DriverManager.getConnection(url, "root", "");
		return conn;
	}

	public static Statement createStatement() throws SQLException {
		if (conn == null)
			conn = getConnection();
		return conn.createStatement();
	}

	public static void close() throws SQLException {
		conn.close();
		conn = null;
	}

	public static void beginTransaction() throws SQLException {
		conn.setAutoCommit(false);
	}

	public static void commitTransction() throws SQLException {
		conn.commit();
		conn.setAutoCommit(true);
	}

	public static PreparedStatement prepareStatement(String sql)
			throws SQLException {
		if (conn == null)
			conn = getConnection();
		return conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Statement stmt = DBUtil.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM Countries");
			while (rs.next()) {
				System.out.println(rs.getString("name"));
			}
			DBUtil.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
